#ifndef NETWORK_CONTROLLER_H
#define NETWORK_CONTROLLER_H

#include <QObject>
#include <QByteArray>
#include <QUdpSocket>
#include <QTcpSocket>
#include <QThread>
#include <QTcpServer>
#include <QNetworkDatagram>
#include <QMap>

// this is not a thread-safe class,any interface invoked in multi-thread maybe will cause unkown falut
class NetworkController : public QObject
{
    Q_OBJECT
public:
    typedef enum{
        TYPE_UDP_SERVER = 0,
        TYPE_TCP_SERVER = 1,
        TYPE_UDP_CLIENT = 2,
        TYPE_TCP_CLIENT = 3,
        TYPE_UNKOWN = 4,
    }NetworkType;
    typedef struct{
        uint32_t len;
        QString addr;
        QString port;
    }RecvResult;

    NetworkType Type();
    NetworkController(NetworkType type,QString ip,uint16_t port);
    int SendData(int8_t *data,uint32_t len);
    RecvResult ReadData(int8_t *data);
    int Close();
    ~NetworkController();
    bool State();
public slots:
    void on_ready_read();
    void on_disconect();
    void on_server_accept();
    void on_accept_error(QAbstractSocket::SocketError socketError);
private slots:
    void on_conected();
    void tcpsock_stateChanged(QAbstractSocket::SocketState);
signals:
    void on_disconnectd();
    void on_connected();
    void on_data_recv();
    void on_conection_ok();
    void on_conection_close();
    void on_send_data(QByteArray);
private:
    NetworkType _checkType(NetworkType);
    NetworkType mType;
    QUdpSocket *mUDP;
    QTcpSocket *mTcp;
    QTcpServer *mTcpServer;
    QIODevice *mCnn;
    QMap<qintptr,QTcpSocket *> m_clients;
    QThread mThread;
    bool mState;
};

#endif // NETWORK_CONTROLLER_H
